package cn.edu.hyit.hjq.volunteems.backend.service.impl;

import cn.edu.hyit.hjq.volunteems.backend.dto.request.ActivityRequest;
import cn.edu.hyit.hjq.volunteems.backend.mapper.ActivityMapper;
import cn.edu.hyit.hjq.volunteems.backend.pojo.Activity;
import cn.edu.hyit.hjq.volunteems.backend.service.ActivityService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.List;


@Service
public class ActivityServiceImpl implements ActivityService {

    private final ActivityMapper activityMapper;

    public ActivityServiceImpl(ActivityMapper activityMapper) {
        this.activityMapper = activityMapper;
    }

    @Override
    public void publishActivity(ActivityRequest request, String userId) {

        // 校验必填字段
        if (!StringUtils.hasText(request.getTitle())) {
            throw new IllegalArgumentException("活动标题不能为空");
        }
        if (!StringUtils.hasText(request.getLocation())) {
            throw new IllegalArgumentException("活动地点不能为空");
        }
        if (request.getCapacity() == null || request.getCapacity() <= 0) {
            throw new IllegalArgumentException("活动人数必须大于 0");
        }
        if (request.getStartTime() == null || request.getEndTime() == null) {
            throw new IllegalArgumentException("活动开始或结束时间不能为空");
        }
        if (request.getStartTime().isAfter(request.getEndTime())) {
            throw new IllegalArgumentException("开始时间不能晚于结束时间");
        }

        Activity activity = new Activity();
        activity.setTitle(request.getTitle());
        activity.setLocation(request.getLocation());
        activity.setCapacity(request.getCapacity());
        activity.setDescription(request.getDescription());
        activity.setStartTime(request.getStartTime());
        activity.setEndTime(request.getEndTime());
        activity.setCreatedBy(userId);
        activity.setCreatedAt(LocalDateTime.now());

        LocalDateTime now = LocalDateTime.now();




        if (now.isBefore(activity.getStartTime())) {
            activity.setStatus(0); // 未开始
        } else if (now.isAfter(activity.getEndTime())) {
            activity.setStatus(2); // 已结束
        } else {
            activity.setStatus(1); // 进行中
        }

        activityMapper.insertActivity(activity);
    }

    @Override
    public List<Activity> getActivitiesSortedByStatus(int page, int size) {
        int offset = Math.max(0, (page - 1) * size);
        return activityMapper.selectByStatusAndTime(offset, size);
    }
}
